package nxu.it.movieapi.service.pg;

import nxu.it.api.common.param.PageQueryParam;
import nxu.it.api.common.result.BasePage;
import nxu.it.api.common.result.Pageable;
import nxu.it.api.model.Comment;
import nxu.it.api.service.CommentService;
import nxu.it.movieapi.service.pg.dao.CommentDao;
import nxu.it.movieapi.service.pg.entity.CommentEntity;
import nxu.it.movieapi.service.pg.mapper.CommentMapper;
import org.seasar.doma.jdbc.SelectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class CommentServicePgImpl implements CommentService {
    @Autowired
    CommentDao commentDao;
    @Autowired
    CommentMapper commentMapper;

    @Override
    public Pageable<Comment> pageByUserId(Integer userId, PageQueryParam pageQueryParam) {
        int totalRow = commentDao.getTotalCountPageByUserId(userId);
        int pagesize = pageQueryParam.getPageSize();
        int pageNumber = pageQueryParam.getPageNumber();
        PageUtil.setOneAsFirstPageNo();
        int totalPage = PageUtil.getTotalPage(totalRow, pagesize);
        int start = PageUtil.getOffset(pageNumber, pagesize);
        SelectOptions options = SelectOptions.get();
        options.limit(pagesize).offset(start);
        List<CommentEntity> commentEntityList = commentDao.pageByUserId(userId, options);
        List<Comment> commentList = commentMapper.fromEntitylist(commentEntityList);
        Pageable<Comment> commentPage = new BasePage<>(commentList, pageNumber, pagesize, totalPage, totalRow);
        return commentPage;
    }

    @Override
    public Pageable<Comment> pageByMovieId(Integer movieId, PageQueryParam pageQueryParam) {
        int totalRow = commentDao.getTotalCountPageByMovieId(movieId);
        int pagesize = pageQueryParam.getPageSize();
        int pageNumber = pageQueryParam.getPageNumber();PageUtil.setOneAsFirstPageNo();
        int totalPage = PageUtil.getTotalPage(totalRow, pagesize);
        int start = PageUtil.getOffset(pageNumber, pagesize);
        SelectOptions options = SelectOptions.get();
        options.limit(pagesize).offset(start);
        List<CommentEntity> commentEntityList = commentDao.pageByMovieId(movieId, options);
        List<Comment> commentList= commentMapper.fromEntitylist(commentEntityList);
        Pageable<Comment> commentPage = new BasePage<>(commentList, pageNumber, pagesize, totalPage, totalRow);
        return commentPage;
    }
}
